# -*- coding: utf-8 -*-
import csv
import xlrd
import sys
import os
import pandas as pd
from collections import OrderedDict
import simplejson as json

#import importlib
#importlib.reload(sys)

reload(sys)
sys.setdefaultencoding('utf-8')

xlsPath = os.getcwd()

def xls_to_json(filename):
    table_list = []
    if filename.find('xlsx') > -1:
        wb = xlrd.open_workbook(filename)
        sh = wb.sheet_by_index(0)
        for rownum in range (2,sh.nrows):
            table = OrderedDict()
            row_values = sh.row_values(rownum)
            for colnum in range (sh.ncols):
                table[sh.cell(1,colnum).value] = row_values[colnum]
            table_list.append(table)
        con = wb.sheet_by_index(1)
        fna = con.cell(0,0).value + ".json"
        with open(fna,'w') as f:
            f.write(json.dumps(table_list))
        move_to_project(fna)

def move_to_project(filename):
    try:
        os.remove("../Client/assets/resources/config/tables/"+filename)
    except Exception, e:
        pass
    os.rename(filename,"../Client/assets/resources/config/tables/"+filename)

if __name__ == '__main__': 
    path = os.getcwd()
    fname_list=[os.path.join(root,fn) for root,dirs,files in os.walk(path) for fn in files]
    for fname in fname_list:
        xls_to_json(fname)
